// pages/production/production.js
const util = require('../../utils/util.js')
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    receiveModel: null, //带过来的数据
    leftValue: '《',
    leftanimation: {},
    knowledgeID: '', //知识id
    knowledgeTitle: '无标题', //标题
    knowledgeDesc: '', //描述
    imageUrl: '', //封面url
    musicNmae: '', //音乐名称
    musicUrl: '', //音乐url
    srcactionflag: '', //大赛id
    show_type: '1', //1代表卡片，2代表全屏幕，三代表长文
    currentIndex: 0,
    indicatorDots: false,
    autoplay: false,
    userInfo: null,
    autoplayVideo: false, //是否正在播放视频 默认为false
    videoUrl: '', //当前播放视频的url
    titleMaxCount: 20,
    descMaxCount: 60,
    forword: '< 上一页',
    backword: '> 下一页',
    pandectValue: '0',
    playVideoImage: '../../image/produce/videoPause.png',
    isPopping: true, //是否已经弹出
    animationPlus: {}, //旋转动画
    animationcollect: {}, //item位移,透明度
    animationTranspond: {}, //item位移,透明度
    isModification: false, //是否修改章节内容 默认为NO
    updateSectionDic: {}, //修改章节的当前数据
    updateSectionIndex: 0, //修改的是第几个章节
    bootomLists: [{
        title: "相册",
        image: "../../image/produce/addForPhoto.png"
      },
      {
        title: "拼图",
        image: "../../image/produce/addForPuzzle.png"
      },
      {
        title: "拍照",
        image: "../../image/produce/addForCamera.png"
      },
      {
        title: "本地视频",
        image: "../../image/produce/addForLocalVideo.png"
      },
      {
        title: "拍摄视频",
        image: "../../image/produce/addForCameraVideo.png"
      },
      {
        title: "文本",
        image: "../../image/produce/addForText.png"
      }
    ],
    dataArr: [{
        //默认只有首页和添加
        section_type: "首页",
      },
      {
        section_type: "添加",
      },
    ],
    showModalStatus: false,
    animationData: {}
  },

  //获取标题和描述
  getTitleWord: function(e) {
    this.setData({
      knowledgeTitle: e.detail.value
    })
  },
  getDescWord: function(e) {
    this.setData({
      knowledgeDesc: e.detail.value
    })
  },

  updateMusic: function() {
    console.log('选择音乐')
    wx: wx.navigateTo({
      url: '../selectBackMusic/selectBackMusic?musicUrl=' + this.data.musicNmae
    })
  },

  previewImage: function(e) {
    console.log('更换封面')
    wx: wx.navigateTo({
      url: '../selectBackImage/selectBackImage?imageUrl=' + this.data.imageUrl
    })
  },

  //添加素材
  showModal: function() {
    var that = this;
    console.log('当前知识id' + that.data.knowledgeID)
    if (that.data.knowledgeID) {
      //有知识id 先判断是否有 标题 描述 背景音乐 封面 更新知识
      var dic = {
        title: that.data.knowledgeTitle,
        description: that.data.knowledgeDesc,
        cover: that.data.imageUrl,
        music: that.data.musicUrl,
        music_name: that.data.musicNmae,
      }
      util.publicRequestWithToken(
        util.KnowledgeHandle + that.data.knowledgeID + '/',
        'PUT',
        dic,
        //sucess
        function(data) {
          that.addMaterial();
        },
        //fail
        function(error) {},
        function() {
          // complete
          wx.hideLoading()
        }
      );
    } else {
      //提交 创建一个新知识
      wx.showLoading({})
      var dic = {
        title: that.data.knowledgeTitle,
        description: that.data.knowledgeDesc,
        cover: that.data.imageUrl,
        music: that.data.musicUrl,
        music_name: that.data.musicNmae,
        struct_id: '1',
      }
      if (that.data.srcactionflag.length > 0) {
        dic.src_action_flag = that.data.srcactionflag
      }
      util.publicRequestWithToken(
        util.KnowledgeHandle,
        'POST',
        dic,
        //sucess
        function(data) {
            that.setData({
              knowledgeID: data.detail.id
            })
            console.log('知识id是' + that.data.knowledgeID)
            that.addMaterial();
        },
        //fail
        function(error) {
          wx.showToast({
            title: '网络开小差了',
            icon: 'none'
          })
        },
        function() {
          // complete
          wx.hideLoading()
        }
      );
    }
  },
  hideModal: function() {
    this.setData({
      isModification: false
    })
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  addMaterial: function() {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },

  switchTab: function(e) {
    var that = this;
    var _isModification = that.data.isModification
    console.log(e.currentTarget.dataset.idx)
    //隐藏底部按钮
    that.hideModal()  
    //这里switch和if else都可以  
    // var dragType = e.target.dataset.idx
    // switch (dragType) {
    //   case '0':
    //     break;
    //   case '1':
    //     break;
    //   case '2':
    //     break;
    //   case '3':
    //     break;
    //   case '4':

    //     break;
    //   case '5':

    //     break;
    //   default:
    //     break;
    // }
    if (e.currentTarget.dataset.idx === 0) {
    } else if (e.currentTarget.dataset.idx === 1) {
      //拼图
    }
    else if (e.currentTarget.dataset.idx === 2) {
      //拍照
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          console.log('拍照照片路径' + res.tempFilePaths[0])
          util.uploadOssFile(res.tempFilePaths[0], "/KlgSectionImage/",
            function(imageUrl) {
              console.log("上传返回图片路径为" + imageUrl)
              that.addImageVideoDic(imageUrl, '', '2', _isModification);
            },
            function(res) {
              console.log("上传失败")
              wx.showToast({
                title: '上传失败',
                icon: 'none'
              })
            });
        },
        fail: function() {
          // fail
          this.setData({
            isModification: false
          })
        },
        complete: function() {
          // complete
        }
      })
    } else if (e.currentTarget.dataset.idx === 2) {
      //本地视频
      wx.chooseVideo({
        sourceType: ['album'],
        maxDuration: 60, //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒
        camera: 'back',
        success: function(res) {
          console.log('本地视频路径' + res)
          //上传阿里云
          util.uploadOssFile(res.tempFilePath, "/KlgSectionVideo/",
            function(videoUrl) {
              console.log("上传返回视频路径为" + videoUrl)
              that.addImageVideoDic(videoUrl, videoUrl, '3', _isModification);
            },
            function(res) {
              console.log("上传失败")
              wx.showToast({
                title: '上传失败',
                icon: 'none'
              })
            });
        },
        fail: function() {
          // fail
          this.setData({
            isModification: false
          })
        },
        complete: function() {
          // complete
        }
      })
    } else if (e.currentTarget.dataset.idx === 3) {
      //拍摄视频
      wx.chooseVideo({
        sourceType: ['camera'],
        maxDuration: 60,
        camera: 'back',
        success: function(res) {
          console.log('拍视频路径' + res.tempFilePaths)
          //上传阿里云
          util.uploadOssFile(res.tempFilePath, "/KlgSectionVideo/",
            function(videoUrl) {
              console.log("上传返回视频路径为" + videoUrl)
              that.addImageVideoDic(videoUrl, videoUrl, '3', _isModification);
            },
            function(res) {
              console.log("上传失败")
              wx.showToast({
                title: '上传失败',
                icon: 'none'
              })
            });
          // that.addImageVideoDic(res.tempFilePaths, '阿里云封面url', '3');
        },
        fail: function() {
          // fail
          this.setData({
            isModification: false
          })
        },
        complete: function() {
          // complete
        }
      })
    } else {
      if (_isModification) {
        //replace成文本
        var tempDic = that.data.updateSectionDic
        const dic = {
          section_type: tempDic.section_type,
          text: tempDic.text,
          voice: tempDic.voice, //语音
          knowledge_id: tempDic.knowledge_id,
          id: tempDic.id,
          section_order: tempDic.section_order,
          index: that.data.updateSectionIndex,
          addType: 'replace'
        }
        wx.navigateTo({
          url: '../editWord/editWord?receiveDic=' + JSON.stringify(dic), //传的为对象
        })
      } else {
        //添加文本
        const dic = {
          section_type: '1',
          text: '',
          voice: '', //语音
          knowledge_id: that.data.knowledgeID,
          count: that.data.dataArr.length,
          addType: 'add'
        }
        wx.navigateTo({
          url: '../editWord/editWord?receiveDic=' + JSON.stringify(dic), //传的为对象
        })
      }

    }
  },
  //修改某一章节文本
  changeDetail: function(e) {
    console.log('修改的章节index为' + e.currentTarget.dataset.idx)
    const index = e.currentTarget.dataset.idx
    var tempDic = this.data.dataArr[index]
    const dic = {
      section_type: tempDic.section_type,
      text: tempDic.text,
      voice: tempDic.voice, //语音
      knowledge_id: tempDic.knowledge_id,
      id: tempDic.id,
      section_order: tempDic.section_order,
      index: index,
      addType: 'change'
    }
    wx.navigateTo({
      url: '../editWord/editWord?receiveDic=' + JSON.stringify(dic), //传的为对象
    })
  },

  //新增一个图片或者视频类型的章节
  addImageVideoDic: function(imageVideoLocalPath, voiceUrl, section_type, _isModification) {
    // section_type 1文本 2图片 3视频 
    var that = this;
    if (_isModification) {
      //修改章节
      var tempDic = that.data.updateSectionDic;
      if (section_type == 2) {
        //图片不更改语音
        var dic = {
          content_url: imageVideoLocalPath,
          voice: tempDic.voice,
          section_type: section_type,
          text: tempDic.text
        }
        //提交
        that.uploadSectionData(util.SectionHandle + tempDic.id + '/', 'PUT', dic, that, '1');
      } else {
        var dic = {
          content_url: imageVideoLocalPath,
          voice: voiceUrl,
          section_type: section_type, //文本为1 图片为2 视频为3
          text: tempDic.text, //固定写1
        }
        //提交
        that.uploadSectionData(util.SectionHandle + tempDic.id + '/', 'POST', dic, that, '1');
      }

    } else {
      //新增一个文本章节 默认从1开始
      var sectionOrderIndex = that.data.dataArr.length - 1; //最后一个view的order + 1
      var sectionOrder = that.data.dataArr.length == 2 ? '1' : sectionOrderIndex.toString();
      var dic = {
        knowledge_id: that.data.knowledgeID,
        section_order: sectionOrder, //默认从1开始
        section_type: section_type, //文本为1 图片为2 视频为3
        struct_order: '1', //固定写1
        text: '',
        voice: voiceUrl,
        content_url: imageVideoLocalPath
      }
      //提交
      that.uploadSectionData(util.SectionHandle, 'POST', dic, that, '0');
    }
  },
  //添加图片或者视频章节内容 修改章节内容 status 0:添加 1：修改
  uploadSectionData: function(url, method, dic, that, status) {
    util.publicRequestWithToken(
      url,
      method,
      dic,
      //sucess
      function(data) {
          var tempDic = {
            section_type: data.detail.section_type,
            text: data.detail.text,
            voice: data.detail.voice,
            id: data.detail.id,
            section_order: data.detail.section_order,
            knowledge_id: data.detail.knowledge_id,
            content_url: data.detail.content_url
          }
          var lastArr = that.data.dataArr;
          if (status == 0) {
            //添加
            lastArr.splice(lastArr.length - 1, 0, tempDic); //在倒数第二位置插入新元素，并返回新的Array
            that.setData({
              dataArr: lastArr,
              pandectValue: lastArr.length - 2
            })
          } else {
            //修改
            lastArr.splice(that.data.updateSectionIndex, 1, tempDic); //指定位置替换掉数据
            that.setData({
              dataArr: lastArr
            })

          }
      },
      //fail
      function(error) {
        wx.showToast({
          title: '网络开小差了',
          icon: 'none'
        })
      },
      function() {
        //完成
        // that.setData({
        //   _isModification:false
        // })
      }

    );
  },
  //预览大图
  previewBigImage: function(e) {
    var imageDic = this.data.dataArr[e.currentTarget.dataset.index];
    console.log('预览大图的路径为' + imageDic.content_url);
    wx.previewImage({
      current: '', // 当前显示图片的http链接
      urls: [imageDic.content_url] // 需要预览的图片http链接列表 必须字符串
    })
  },
  //播放或者暂停视频
  playOrPause: function(e) {
    this.setData({
      autoplayVideo: !this.data.autoplayVideo
    })
    if (this.data.autoplayVideo) {
      //开始播放视频
      //取到视频url
      var dic = this.data.dataArr[e.currentTarget.dataset.index];
      this.setData({
        videoUrl: dic.content_url
      })
    }
  },
  //视频播放代理事件
  videoBindplay: function() {
    console.log('开始播放')
  },
  videoBindpause: function() {
    console.log('暂停播放')
  },
  videoBindended: function() {
    console.log('播放结束')
    this.setData({
      autoplayVideo: false
    })
  },
  videoBinderror: function() {
    console.log('播放出错')
    this.setData({
      autoplayVideo: false
    })
  },

  //停止视频的播放
  stopPlayVideo: function() {
    var videoContext = wx.createVideoContext('video')
    videoContext.stop()
    this.setData({
      autoplayVideo: false
    })
  },
  //上一页
  forword: function() {
    //如果正在播放视频就停止
    if (this.data.autoplayVideo) {
      this.stopPlayVideo()
    }
    this.setData({
      currentIndex: this.data.currentIndex - 1
    })

  },
  //下一页
  backword: function() {
    //如果正在播放视频就停止
    if (this.data.autoplayVideo) {
      this.stopPlayVideo()
    }
    this.setData({
      currentIndex: this.data.currentIndex + 1
    })
  },

  bindanimationfinish: function(e) {
    //如果正在播放视频就停止
    // if (this.data.autoplayVideo) {
    //   this.stopPlayVideo()
    // }
  },
  //swiper滚动事件
  bindChange: function(e) {
    //如果正在播放视频就停止
    if (this.data.autoplayVideo) {
      this.stopPlayVideo()
    }
    console.log('当前第' + e.detail.current + '页')
    var that = this;
    that.setData({
      currentIndex: e.detail.current
    });
    //第一页或者最后一页
    if (e.detail.current == 0 || e.detail.current == that.data.dataArr.length - 1) {
      that.setData({
        pandectValue: that.data.dataArr.length - 2
      });
    } else {
      that.setData({
        pandectValue: e.detail.current + '/' + (that.data.dataArr.length - 2)
      });
    }

  },
  //删除某一个素材
  delte: function(e) {
    var that = this;
    console.log(e.currentTarget.dataset.id);
    var sectionDic = that.data.dataArr[e.currentTarget.dataset.id]
    //弹出框
    wx.showModal({
      title: '',
      content: '确定删除吗？',
      confirmColor: '#0084ff',
      success: function(res) {
        if (res.confirm) {
          util.publicRequestWithToken(
            util.SectionHandle + sectionDic.id + '/',
            'DELETE',
            null,
            //sucess
            function(data) {
              var lastArr = that.data.dataArr;
              lastArr.splice(e.currentTarget.dataset.id, 1); //删除指定下标元素
              that.setData({
                dataArr: lastArr
              })
            },
            //fail
            function(error) {},
            function() {
              // complete
              wx.hideLoading()
            }
          );
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  //修改某一个素材
  update: function(e) {
    console.log(e.currentTarget.dataset.id)
    this.setData({
      updateSectionDic: this.data.dataArr[e.currentTarget.dataset.id],
      isModification: true,
      updateSectionIndex: e.currentTarget.dataset.id
    })
    this.setData();
    console.log('修改的dic' + this.data.updateSectionDic)
    this.addMaterial();
  },

  //预览发布
  toPreview: function() {
    var that = this;
    that.setData({
      isPopping: false
    })
    that.plus();
    //判断是否有素材
    if (that.data.dataArr.length == 2) {
      wx: wx.showToast({
        title: '请先添加素材',
        icon: 'none'
      })
    }
    else {
      // 更新知识后跳转
      var dic = {
        title: that.data.knowledgeTitle,
        description: that.data.knowledgeDesc,
        cover: that.data.imageUrl,
        music: that.data.musicUrl,
        music_name: that.data.musicNmae,
      }
      util.publicRequestWithToken(
        util.KnowledgeHandle + that.data.knowledgeID + '/',
        'PUT',
        dic,
        //sucess
        function(data) {
            //跳转
            const dic = {
              knowledge_id: that.data.knowledgeID,
              title: that.data.knowledgeTitle,
              description: that.data.knowledgeDesc,
              cover: that.data.imageUrl,
              musicName: that.data.musicNmae,
              music: that.data.musicUrl,
              srcactionflag: that.data.srcactionflag,
              show_type: that.data.show_type
            }
            wx.navigateTo({
              url: '../releaseGuide/releaseGuide?receiveDic=' + JSON.stringify(dic), //传的为对象
            })
        },
        //fail
        function(error) {},
        function() {
          // complete
          wx.hideLoading()
        }
      );
    }
  },
  //删除该作品
  toDelete: function() {
    var that = this;
    if (that.data.knowledgeID) {
      //删除
      util.publicRequestWithToken(
        util.KnowledgeHandle + that.data.knowledgeID + '/',
        'DELETE',
        null,
        //sucess
        function(data) {
            //刷新草稿箱
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 2]; //上一个页面
            prevPage.setData({
              page: 1
            });
            prevPage.getDetailLists();
            wx.navigateBack({
              delta: 1,
            })
        },
        //fail
        function(error) {},
        function() {
          // complete
          wx.hideLoading()
        }
      );
    } else {
      //直接返回
      wx.navigateBack({
        delta: 1,
      })
    }
  },
  //点击弹出
  plus: function() {
    if (this.data.isPopping) {
      //缩回动画
      this.popp();
      this.setData({
        isPopping: false
      })
    } else {
      //弹出动画
      this.takeback();
      this.setData({
        isPopping: true
      })
    }
  },
  input: function() {
    console.log("input")
  },
  transpond: function() {
    console.log("transpond")
  },
  collect: function() {
    console.log("collect")
  },



  //弹出动画
  popp: function() {
    //plus顺时针旋转
    var animationPlus = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    var animationcollect = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    var animationTranspond = wx.createAnimation({
      duration: 200,
      // timingFunction: 'ease-out'
    })

    animationPlus.rotateZ(90).step();
    animationcollect.translate(-80, -60).rotateZ(0).opacity(1).step();
    animationTranspond.translate(-20, -90).rotateZ(0).opacity(1).step();
    this.setData({
      animationPlus: animationPlus.export(),
      animationcollect: animationcollect.export(),
      animationTranspond: animationTranspond.export(),
    })
  },
  //收回动画
  takeback: function() {
    //plus逆时针旋转
    var animationPlus = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    var animationcollect = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    var animationTranspond = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })

    animationPlus.rotateZ(0).step();
    animationcollect.translate(0, 0).rotateZ(0).opacity(0).step();
    animationTranspond.translate(0, 0).rotateZ(0).opacity(0).step();
    this.setData({
      animationPlus: animationPlus.export(),
      animationcollect: animationcollect.export(),
      animationTranspond: animationTranspond.export(),
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    console.log('获取头像昵称等信息' + app.globalData.userInfo)
    // 检测是否存在用户信息
    if (app.globalData.userInfo != null) {
      that.setData({
        userInfo: app.globalData.userInfo
      })
    } else {
      app.getUserInfo()
    }

    console.log("接收到的参数是obj=" + options.receiveModel); //此处打印出来的仅仅是字符串 需要解析，解析如下
    if (options.receiveModel) {
      that.setData({
        receiveModel: JSON.parse(options.receiveModel)
      })
      if (that.data.receiveModel.pushType == 1) {
        //参与投稿 拿到大赛的id
        that.setData({
          srcactionflag: that.data.receiveModel.src_action_flag
        })
      } else {
        //草稿箱
        that.setData({
          knowledgeID: that.data.receiveModel.id, //知识id
          knowledgeTitle: that.data.receiveModel.title, //标题
          knowledgeDesc: that.data.receiveModel.description, //描述
          imageUrl: that.data.receiveModel.cover, //封面url
          musicNmae: that.data.receiveModel.music_name, //音乐名称
          musicUrl: that.data.receiveModel.music, //音乐url
        })
        var dic = {
          knowledge_id: that.data.knowledgeID,
          page_size_count: 1000
        }
        util.publicRequestWithToken(
          util.SectionHandle,
          'GET',
          dic,
          //sucess
          function(data) {
              console.log('数据为' + data)
              var lastArr = that.data.dataArr;
              var receiveArr = data.detail.results;
              if (receiveArr.length > 0) {
                //添加到dataarr里 遍历
                receiveArr.map((item, index) => {
                  lastArr.splice(lastArr.length - 1, 0, item); //在倒数第二位置插入新元素，并返回新的Array
                })
                that.setData({
                  dataArr: lastArr,
                })
              }
          },
          //fail
          function(error) {},
          function() {
            // complete
            wx.hideLoading()
          }
        );
      }
    }

    //获取总页数
    that.setData({
      pandectValue: that.data.dataArr.length - 2
    });

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    //获取背景图片
    var that = this;
    wx.getStorage({
      key: 'knowledgeBackImage',
      success: function(res) {
        that.setData({
          imageUrl: res.data
        })
      },
      complete: function() {
        //移除本地图片key
        wx.removeStorage({
          key: 'knowledgeBackImage',
          success: function(res) {}
        })
      }
    })

    //左箭头动画
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'linear',
    })
    this.animation = animation
    var next = true;
    //连续动画关键步骤
    setInterval(function() {
      if (next) {
        //平移动画
        this.animation.translate(-20, 0).step()
        next = !next;
      } else {
        this.animation.translate(0, 0).step()
        next = !next;
      }
      this.setData({
        leftanimation: animation.export()
      })
    }.bind(this), 500)

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})